package gw.com.android.upgrade;

import android.text.TextUtils;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.BuildConfig;
import com.gwtsz.gts2.hx.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.Https;
import gw.com.android.utils.ENV;
import gw.com.jni.library.terminal.GTSConst;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;
import www.com.library.dialog.ToastPopWindow;

/**
 * @author jett
 * @since 2018-11-26.
 */
public class UpgradeHelper {

    private final String TAG = "UpgradeHelper";

    private static final UpgradeHelper instance = new UpgradeHelper();
    private final List<String> grayList;
    private boolean dialogShowed = false;

    private UpgradeHelper() {
        grayList = Collections.synchronizedList(new ArrayList<String>());
    }

    public static UpgradeHelper getInstance() {
        return instance;
    }

    public void start() {
        if (dialogShowed) {
            Logger.i(TAG, "upgrade dialog already showed...");
            return;
        }
        String mCurName = GTConfig.instance().mCurName;
        if (grayList.contains(mCurName)) {
            Logger.i(TAG, "this user was requested. username = " + mCurName);
            return;
        }
        grayList.add(mCurName);
        request(mCurName, false);
    }

    public void reStart() {
        request(GTConfig.instance().mCurName, true);
    }

    private void request(String accountNo, final boolean renew) {
        String host = ENV.isUat() ? "http://192.168.35.95:8080/" : "https://appcfg.hx9999.com/";
        //String url = host + "http://192.168.35.95:8280/api/app/version/queryVersion";
        String url = host + "api/app/version/queryVersion";
        new Https(url).addParam("company_id", ConfigUtil.instance().mConfigObject.optInt(ConfigType.COMPANY_ID_TAG) + "")
                .addParam("app_id", BuildConfig.APP_ID + "")
                //.addParam("version","110")
                .addParam("plat_type_key", "android")
                .addParam("account_no", accountNo == null ? "" : accountNo)
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        dealSuccess(renew, result);
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        dealFailure(renew, e);
                    }
                });
    }

    private void dealSuccess(boolean renew, String result) {
        if (!renew && dialogShowed) {
            Logger.i(TAG, "onSuccess upgrade dialog already showed...");
            return;
        }
        parse(result);
        if (renew && !dialogShowed) {
            // 设置中进行版本更新检测，未发现新版本
            new ToastPopWindow(AppMain.getApp(), AppMain.getApp().getString(R.string.app_upgrade_no_version_update)).show();
        }
        if (!renew && !dialogShowed) {
            RxBus.getInstance().post(GTSConst.REPLY_POP_ADS_AFTER_UGPRADE, 0);
        }
    }

    private void dealFailure(boolean renew, Exception e) {
        Logger.e(TAG, e);
        if (!renew) {
            RxBus.getInstance().post(GTSConst.REPLY_POP_ADS_AFTER_UGPRADE, 0);
        }
    }

    private void parse(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject dataJson = jsonObject.optJSONObject("data");
            if (dataJson != null) {
                String url = dataJson.optString("url");
                String version = dataJson.optString("version");
                String isForce = dataJson.optString("isForce");
                Logger.i(TAG, "version = " + version + " isForce = " + isForce + " url = " + url);
                if (!TextUtils.isEmpty(url) && isNewVersion(version)) {
                    //boolean isGray = dataJson.optBoolean("isGray");
                    //String updateStatus = dataJson.optString("updateStatus");
                    String comment = dataJson.optString("comment");
                    if ("1".equals(isForce)) {
                        dialogShowed = GTConfig.instance().hasNewVersion = true;
                        new UpgradeDialog(false, url, comment).show();
                    } else if ("2".equals(isForce)) {
                        dialogShowed = GTConfig.instance().hasNewVersion = true;
                        new UpgradeDialog(true, url, comment).show();
                    } else {
                        Logger.i(TAG, "needn't upgrade . isForce = " + isForce);
                    }
                }
                return;
            }
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
        Logger.i(TAG, "parse result = " + result);
    }

    private boolean isNewVersion(String version) {
        if (TextUtils.isEmpty(version)) {
            return false;
        }
        String versionCode = version.replaceAll("[^\\d]", "");
        try {
            int code = Integer.parseInt(versionCode);
            return code > BuildConfig.VERSION_CODE;
        } catch (NumberFormatException e) {
            Logger.e(TAG, e);
        }
        Logger.i(TAG, "isNewVersion = false and version = " + version);
        return false;
    }

}
